package DD.Game;

import java.util.List;

import Core.GameTime;
import Core.SpriteBatch;
import Screen.Draw2D;
import Screen.Screen;
import android.app.Activity;
import android.graphics.Canvas;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;

public class Game extends Activity {
	
	private boolean isRunning = true;
	private boolean Enable = true;
	private boolean Visible = true;
	private Canvas c;
	private GameTime gameTime;
	private SpriteBatch spriteBatch;
	private List<Screen> listScreen;
	//Code added
	private Draw2D draw2d;
	//Sound variable
	private SoundPool sounds;
	private int sExplosion;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //code edit----------
        //setContentView(R.layout.main);
        draw2d = new Draw2D(this);
        setContentView(draw2d);
        sounds = new SoundPool(10, AudioManager.STREAM_MUSIC,0);
        sExplosion = sounds.load(this, R.raw.explosion, 1);
        sounds.play(sExplosion, 5.0f, 5.0f, 0, 1, 1.5f);
        //end edit--------
        
        /*this.gameTime = new GameTime();
        View v = findViewById(R.id.view_main);
        Bitmap bm = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);        
        c = new Canvas(bm);
        this.spriteBatch = new SpriteBatch(c);
        try{
        	run();	
        }
        catch (InterruptedException iE) {
			// TODO: handle exception
        	
		}
        finally{
        	
        }*/
    }
    
    public void run() throws InterruptedException{
    	long startTime, endTime;
    	int freqTime = 40;
    	while (isRunning) {
    		startTime = System.currentTimeMillis();
            if(Enable){
                update();
            }
            if(Visible){
                draw();
            }
            endTime = System.currentTimeMillis();
            int delay = (int)(freqTime - (endTime-startTime)); // 25fps
            if(delay<0){
            	delay = 0;
            	gameTime.Inscrease(endTime - startTime);
            }
            else{
            	gameTime.Inscrease(freqTime);
            }
            //sleep            
            Thread.sleep(delay);
            
        }
    }
    
    private void update() {
    	//update all screen
        for(int i = 0 ; i < listScreen.size(); i++){
        	Screen screen = listScreen.get(i);
        	screen.update(gameTime);	
        }
    }
    
    private void draw() {
    	//draw all screen
    	for(int i = 0 ; i < listScreen.size(); i++){
        	Screen screen = listScreen.get(i);
        	screen.draw(gameTime, spriteBatch);
        	View v = findViewById(R.id.view_main);
        	//draw canvas to view - other name : double buffering ( canvas is back buffer )
        	v.draw(c);
        }
    }
}